export default {
  data () {
    return {
      // 折线图
      myChartLine: null,
      // option
      chartOptionLine: {},
      // 温湿度图标图片
      temperatureIcon: require('@/static/images/temperature.png'),
      humidityIcon: require('@/static/images/humidity.png'),
      // 秒
      maxIntervalTime: 1000
    };
  },
  methods: {
    // 初始化温湿度线的数据
    _initMarkLineData (degreeData) {
      const markLineTemperatureData = []
      if (degreeData.minTemperature) markLineTemperatureData.push({ yAxis: degreeData.minTemperature })
      if (degreeData.maxTemperature) markLineTemperatureData.push({ yAxis: degreeData.maxTemperature })

      const markLineHumidityData = []
      if (degreeData.minHumidity) markLineHumidityData.push({ yAxis: degreeData.minHumidity })
      if (degreeData.maxHumidity) markLineHumidityData.push({ yAxis: degreeData.maxHumidity })

      return { markLineTemperatureData, markLineHumidityData }
    },
    // 格式化y轴数据
    _formatYData (value) {
      const { temperatureData, humidityData, degreeData } = value
      let max = 0
      let min = 100
      const newData = humidityData ? [...temperatureData, ...humidityData] : [...temperatureData]
      newData.forEach(item => {
        max = max <= item ? item : max
        min = min >= item ? item : min
      })
      if (degreeData.maxTemperature > max) max = degreeData.maxTemperature
      if (degreeData.minTemperature < min) min = degreeData.minTemperature
      if (degreeData.maxHumidity > max) max = degreeData.maxHumidity
      if (degreeData.minHumidity < min) min = degreeData.minHumidity
      return [
        {
          max: parseFloat((max + 5).toFixed(1)),
          min: parseFloat((min - 5).toFixed(1)),
          interval: 10,
          axisLine: {
            show: true,
            symbol: ['none', 'path://M5,20 L5,5 L8,8 L5,2 L2,8 L5,5 L5.3,6 L5.3,20'],
            symbolOffset: 5,
            symbolSize: [35, 38]
          },
          axisTick: {
            show: true
          }
        }
      ]
    },
    // 根据接口返回的数据长度判断dataZoom的显示比例
    _setProportionData (data) {
      const length = data.length
      let end = 0
      if (length >= 0 && length < 50) {
        end = 100
      } else {
        end = 100 * (75 / length)
      }
      return { start: 0, end }
    },
    // 根据数据判断温湿度/温度的渲染
    _seriesData (value) {
      const { temperatureData, humidityData, markLineTemperatureData, markLineHumidityData, degreeData } = value
      const temperature = {
        name: '温度',
        type: 'line',
        data: temperatureData,
        label: { show: true },
        markLine: {
          symbol: 'none',
          itemStyle: {
            normal: {
              label: {
                formatter (item) {
                  if (degreeData.maxTemperature == item.value) {
                    return '最高 ' + item.value + '℃'
                  } else {
                    return '最低 ' + item.value + '℃'
                  }
                }
              }
            }
          },
          silent: true,
          data: markLineTemperatureData
        }
      }
      const humidity = {
        name: '湿度',
        type: 'line',
        data: humidityData,
        label: { show: true },
        markLine: {
          symbol: 'none',
          itemStyle: {
            normal: {
              label: {
                formatter (item) {
                  if (degreeData.maxHumidity == item.value) {
                    return '最高' + item.value + '%RH'
                  } else {
                    return '最低' + item.value + '%RH'
                  }
                }
              }
            }
          },
          silent: true,
          data: markLineHumidityData
        }
      }
      if (humidityData) return [temperature, humidity]
      else return [temperature]
    },
    _setEcharts (data) {
      const { degreeData, temperatureData, humidityData, xAxisData, tipList } = data
      // markLineData 数据集成
      const { markLineTemperatureData, markLineHumidityData } = this._initMarkLineData(degreeData)
      // 根据接口返回的数据，获取数据和温湿度设定的最大值和最小值，再将计算出来的数据赋值给y轴
      const yData = this._formatYData({ degreeData, temperatureData, humidityData })
      // 根据接口返回的数组中的 length ，来判断初始化显示的比例
      const proportion = this._setProportionData(xAxisData)
      // 根据数据判断温湿度/温度的渲染
      const seriesData = this._seriesData({ temperatureData, humidityData, markLineTemperatureData, markLineHumidityData, degreeData })
      // 基于准备好的dom，初始化echarts实例
      const myChart = this.$echarts.init(document.getElementById('myChartLine'))
      // 将 mychart 存入到 data，做一个备份，后面需要使用 setOption api刷新图表数据
      this.myChart = myChart
      const that = this
      const text = humidityData ? '温湿度' : '温度'
      const chartOptionLine = {
        color: ['#ff374b', '#569d41'],
        title: { text: text, left: '158px', top: 0 },
        tooltip: {
          trigger: 'axis',
          formatter (params) {
            let res = '<pre style="padding:0 15px">'
            res += `<p>${params[0].axisValue}</p>`
            params.forEach(item => {
              const seriesName = item.seriesName
              if (item.seriesName === '温度') {
                res += `<p style=display:flex;align-items:center><img src=${that.temperatureIcon} style=color:${item.color};width:14px;height:18px;margin-right:5px></img>${seriesName}: ${item.value}℃</p>`
              } else if (item.seriesName === '湿度') {
                res += `<p style=display:flex;align-items:center><img src=${that.humidityIcon} style=color:${item.color};width:14px;height:14px;margin-right:5px></img>${seriesName}: ${item.value}%RH</p>`
              }
            })
            res += '</pre>'
            return res
          }
        },
        legend: {
          orient: 'vertical',
          right: 400,
          formatter (name) {
            if (name === '温度') return tipList[0]
            if (name === '湿度') return tipList[1]
          }
        },
        toolbox: {
          show: true,
          left: 'center',
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        dataZoom: [{
          type: 'slider',
          show: true,
          start: proportion.start,
          end: proportion.end,
          backgroundColor: "var(--prev-bg-white)",
          fillerColor: 'rgba(208,216,226, 0.5)',
          borderColor: "var(--prev-border-color-extra-grey)",
          brushSelect: false,
          dataBackground: {
            lineStyle: {
              color: 'var(--prev-border-color-extra-grey)',
              width: 1,
              type: 'dotted',
              dashOffset: 0,
              cap: 'butt',
              join: 'bevel',
              miterLimit: 10,
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              opacity: 0
            },
            areaStyle: {
              color: '#eceef0',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.3)',
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              opacity: 1
            }
          },
          textStyle: {
            color: '#000',
            fontSize: 11
          },
        }, {
          type: 'inside',
        }],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: {
            symbol: ['none', 'path://M5, 20 L5, 5 L8, 8 L5, 2 L2, 8 L5, 5 L5.3, 6 L5.3, 20'],
            symbolOffset: 5,
            symbolSize: [35, 38]
          },
          data: xAxisData
        },
        yAxis: yData,
        series: seriesData
      }
      // 使用刚指定的配置项和数据显示图表
      myChart.setOption(chartOptionLine, true)
      // 图表节点点击事件
      myChart.on('click', params => {
        console.log("params---------", params);
        // 获取 vuex 中的变量，初始化为0
        const time = this.mapIntervalTime
        // 获取当前时间(毫秒数)
        const currentTime = Date.now()
        // 获取(当前时间毫秒数 - vuex中的变量存储的毫秒数)
        const intervalTime = currentTime - time
        console.log('time,currentTime,intervalTime-------', time, currentTime, intervalTime);
        // 如果time不为空并且间隔时间小于 maxIntervalTime秒
        if (time && intervalTime < this.maxIntervalTime) {
          this.$message.warning("操作太频繁，请稍后重试")
        } else {
          this.$store.commit('common/MAP_INTERVAL_TIME', Date.now())
          this.getPosition(params)
        }
      })
    },
    // 根据温湿度的值来显示tip标题文本
    _getTipListText (degree) {
      let tipListFirst = '温度'
      let tipListSecond = '湿度'
      if (degree.maxTemperature || degree.maxTemperature === 0) tipListFirst += `    最高${degree.maxTemperature}℃`
      if (degree.minTemperature || degree.minTemperature === 0) tipListFirst += `    最低${degree.minTemperature}℃`
      if (degree.maxHumidity || degree.maxHumidity === 0) tipListSecond += `    最高${degree.maxHumidity}%RH`
      if (degree.minHumidity || degree.minHumidity === 0) tipListSecond += `    最低${degree.minHumidity}%RH`
      return [tipListFirst, tipListSecond]
    }
  }
}